package com.leecode.base;

/**
 * @Author: yaoshubin
 * @Date: 2022-12-10 16:46
 * @description : 在有序数组arr[] 找出 >= 某个数的最小位置
 * <p>
 * 特点：
 * 1）有序的前提下
 * 2）一次砍掉一半
 */
public class Index_05_二分法找最小位置 {

    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 5, 7, 10, 12};
        //int index = findMostLeftIndex(arr, 2);  // 记得检验边界，如1，12，100
        int index = findMostRirhtIndex(arr, 2);  //记得检验边界，如1，12，100
        System.out.println(index);
    }


    /**
     * 查找数组中>=某个数的最左位置
     *
     * @param arr
     * @param num
     * @return
     */
    public static int findMostLeftIndex(int[] arr, int num) {
        //处理边界
        if (arr == null || arr.length == 0) {
            return -1;
        }
        int left = 0;
        int right = arr.length - 1;
        int index = -1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] >= num) {
                index = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return index;
    }


    /**
     * 查找数组中 <=某个数的最右位置
     *
     * @param arr
     * @param num
     * @return
     */
    public static int findMostRirhtIndex(int[] arr, int num) {
        //处理边界
        if (arr == null || arr.length == 0) {
            return -1;
        }
        int left = 0;
        int right = arr.length - 1;
        int index = -1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] <= num) {
                index = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return index;
    }
}
